/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.permission.template.impl;

import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.permission.PermissionOperationTypeEnum;
import com.je.rbac.service.permission.PermissionTypeEnum;
import com.je.rbac.service.permission.template.PcFuncBaseService;
import com.je.rbac.service.permission.template.PermissionPcFuncTemplateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PcFuncBaseServiceImpl extends AbstractPermissionTemplateService implements PcFuncBaseService {

    @Autowired
    private MetaService metaService;

    @Override
    public String formatPcFuncConfigTemplate(String funcCode) {
        return formatTemplate(PermissionPcFuncTemplateEnum.FUNC_PC_CONFIG.getTemplate(), Entry.build("funcCode", funcCode));
    }

    @Override
    public String formatPcFuncShowTemplate(String funcCode) {
        return formatTemplate(PermissionPcFuncTemplateEnum.FUNC_PC_SHOW.getTemplate(), Entry.build("funcCode", funcCode));
    }

    @Override
    public String formatPcFuncUpdateTemplate(String funcCode) {
        return formatTemplate(PermissionPcFuncTemplateEnum.FUNC_PC_UPDATE.getTemplate(), Entry.build("funcCode", funcCode));
    }

    @Override
    public String formatPcFuncDeleteTemplate(String funcCode) {
        return formatTemplate(PermissionPcFuncTemplateEnum.FUNC_PC_DELETE.getTemplate(), Entry.build("funcCode", funcCode));
    }

    @Override
    public DynaBean writePcFuncConfigPermission(String funcCode, boolean checkDb) {
        if (checkDb) {
            List<DynaBean> dynaBeans = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncConfigTemplate(funcCode)));
            if (dynaBeans != null && dynaBeans.size() > 0) {
                metaService.delete("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncConfigTemplate(funcCode))
                        .ne("JE_RBAC_PERM_ID", dynaBeans.get(0).getStr("JE_RBAC_PERM_ID")));
                return dynaBeans.get(0);
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.FUNC_PC_CONFIG, PermissionPcFuncTemplateEnum.FUNC_PC_CONFIG.getName(),
                formatPcFuncConfigTemplate(funcCode), funcCode, PermissionOperationTypeEnum.CONFIG);
    }

    @Override
    public DynaBean findPcFuncConfigPermission(String funcCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncConfigTemplate(funcCode)));
    }

    @Override
    public DynaBean writePcFuncShowPermission(String funcCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncShowTemplate(funcCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.FUNC_PC_BASE, PermissionPcFuncTemplateEnum.FUNC_PC_SHOW.getName(),
                formatPcFuncShowTemplate(funcCode), funcCode, PermissionOperationTypeEnum.SHOW);
    }

    @Override
    public DynaBean findPcFuncShowPermission(String funcCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncShowTemplate(funcCode)));
    }

    @Override
    public DynaBean writePcFuncUpdatePermission(String funcCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncUpdateTemplate(funcCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.FUNC_PC_BASE, PermissionPcFuncTemplateEnum.FUNC_PC_UPDATE.getName(),
                formatPcFuncUpdateTemplate(funcCode), funcCode, PermissionOperationTypeEnum.UPDATE);
    }

    @Override
    public DynaBean findPcFuncUpdatePermission(String funcCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncUpdateTemplate(funcCode)));
    }

    @Override
    public DynaBean writePcFuncDeletePermission(String funcCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncDeleteTemplate(funcCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.FUNC_PC_BASE, PermissionPcFuncTemplateEnum.FUNC_PC_DELETE.getName(),
                formatPcFuncDeleteTemplate(funcCode), funcCode, PermissionOperationTypeEnum.DELETE);
    }

    @Override
    public DynaBean findPcFuncDeletePermission(String funcCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncDeleteTemplate(funcCode)));
    }

    @Override
    public List<DynaBean> writePcFuncBasePermission(String funcCode, boolean update, boolean delete, boolean config) {
        //如果没有配置权限，则不给此功能的更改和删除权限
        List<String> permCodeList = Lists.newArrayList(
                formatPcFuncShowTemplate(funcCode)
        );
        if (update) {
            permCodeList.add(formatPcFuncUpdateTemplate(funcCode));
        }
        if (delete) {
            permCodeList.add(formatPcFuncDeleteTemplate(funcCode));
        }
        if (config) {
            permCodeList.add(formatPcFuncConfigTemplate(funcCode));
        }
        List<DynaBean> beanList = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().in("PERM_CODE", permCodeList));

        //此处逻辑在于校验单个权限的添加是否还需要校验，用于提升性能，不用每个添加都查询数据库
        DynaBean showBean = null;
        DynaBean updateBean = null;
        DynaBean deleteBean = null;
        DynaBean configBean = null;
        for (DynaBean eachBean : beanList) {
            if (formatPcFuncShowTemplate(funcCode).equals(eachBean.getStr("PERM_CODE"))) {
                showBean = eachBean;
                continue;
            }
            //如果没有配置权限，则只操作展示权限
            if (update && formatPcFuncUpdateTemplate(funcCode).equals(eachBean.getStr("PERM_CODE"))) {
                updateBean = eachBean;
                continue;
            }
            if (delete && formatPcFuncDeleteTemplate(funcCode).equals(eachBean.getStr("PERM_CODE"))) {
                deleteBean = eachBean;
                continue;
            }
            if (config && formatPcFuncConfigTemplate(funcCode).equals(eachBean.getStr("PERM_CODE"))) {
                configBean = eachBean;
                continue;
            }
        }

        List<DynaBean> resultList = new ArrayList<>();
        if (showBean != null) {
            resultList.add(showBean);
        } else {
            resultList.add(writePcFuncShowPermission(funcCode, false));
        }

        if (update) {
            if (updateBean != null) {
                resultList.add(updateBean);
            } else {
                resultList.add(writePcFuncUpdatePermission(funcCode, false));
            }
        }

        if (delete) {
            if (deleteBean != null) {
                resultList.add(deleteBean);
            } else {
                resultList.add(writePcFuncDeletePermission(funcCode, false));
            }
        }

        if (config) {
            if (configBean != null) {
                resultList.add(configBean);
            } else {
                resultList.add(writePcFuncConfigPermission(funcCode, false));
            }
        }

        return resultList;
    }

    @Override
    public List<DynaBean> findPcFuncBasePermission(String funcCode, boolean update, boolean delete, boolean config) {
        List<String> permCodeList = Lists.newArrayList(formatPcFuncShowTemplate(funcCode));
        if (update) {
            permCodeList.add(formatPcFuncUpdateTemplate(funcCode));
        }
        if (delete) {
            permCodeList.add(formatPcFuncDeleteTemplate(funcCode));
        }
        if (config) {
            permCodeList.add(formatPcFuncConfigTemplate(funcCode));
        }
        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().in("PERM_CODE", permCodeList));
    }

    @Override
    public void modifyPermCode(String oldFuncCode, String newFuncCode) {
        List<String> permCodeList = Lists.newArrayList(formatPcFuncShowTemplate(oldFuncCode),
                formatPcFuncUpdateTemplate(oldFuncCode),
                formatPcFuncDeleteTemplate(oldFuncCode),
                formatPcFuncConfigTemplate(oldFuncCode));
        List<DynaBean> oldFuncPermBeanList = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().in("PERM_CODE", permCodeList));
        for (int i = 0; oldFuncPermBeanList != null && !oldFuncPermBeanList.isEmpty() && i < oldFuncPermBeanList.size(); i++) {
            if (PermissionOperationTypeEnum.SHOW.getCode().equals(oldFuncPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldFuncPermBeanList.get(i).set("PERM_CODE", formatPcFuncShowTemplate(newFuncCode));
            } else if (PermissionOperationTypeEnum.UPDATE.getCode().equals(oldFuncPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldFuncPermBeanList.get(i).set("PERM_CODE", formatPcFuncUpdateTemplate(newFuncCode));
            } else if (PermissionOperationTypeEnum.DELETE.getCode().equals(oldFuncPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldFuncPermBeanList.get(i).set("PERM_CODE", formatPcFuncDeleteTemplate(newFuncCode));
            } else if (PermissionOperationTypeEnum.CONFIG.getCode().equals(oldFuncPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldFuncPermBeanList.get(i).set("PERM_CODE", formatPcFuncConfigTemplate(newFuncCode));
            }
            metaService.update(oldFuncPermBeanList.get(i));
        }
    }

}
